package com.dc.bobaoge.project.base.core.injector.method;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.dc.bobaoge.project.base.core.injector.constant.BaseMybatisConstant;
import org.apache.ibatis.mapping.MappedStatement;

/**
 * 根据 whereEntity 条件，更新记录
 *
 * @author hubin
 * @since 2018-04-06
 */
public class CustomUpdate extends AbstractMethod {

    /**
     * 待替换的字符串
     */
    private static final String REPLACEMENT_TEXT = "<if test=\"ew != null and ew.sqlSet != null\">${ew.sqlSet}</if>";

    /**
     * 替换成的字符串
     */
    private static final String REPLACEMENT_STR = BaseMybatisConstant.UPDATE_FLAG_VALUE + "," + REPLACEMENT_TEXT;

    public CustomUpdate() {
        this(SqlMethod.UPDATE.getMethod());
    }

    /**
     * @param name 方法名
     * @since 3.5.0
     */
    public CustomUpdate(String name) {
        super(name);
    }

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        var sqlMethod = SqlMethod.UPDATE;
        var sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
                sqlSet(true, true, tableInfo, true, ENTITY, ENTITY_DOT),
                sqlWhereEntityWrapper(true, tableInfo), sqlComment());
        sql = sql.replace(REPLACEMENT_TEXT, REPLACEMENT_STR);
        var sqlSource = super.createSqlSource(configuration, sql, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, methodName, sqlSource);
    }
}
